/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.agile.main;

import com.agile.gerberviewer.Plotter;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.border.EtchedBorder;

/**
 *
 * @author Roderick
 */
public class Frame extends JFrame {

    Properties prop = new Properties();

    JTextArea gCodeFile = new JTextArea();
    JTextArea gerberFile = new JTextArea();

    JPanel gerberViewerPanel = new JPanel();
    JPanel gCodeViewerPanel = new JPanel();

    public Frame() {
        getProperties();
        this.setTitle(prop.getProperty("title"));
        makeMenu();

        makeTool();

        JPanel content = new JPanel();
        content.setLayout(new GridLayout(1, 2));

        JPanel gerberPanel = new JPanel();
        gerberPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Gerber"));
        gerberPanel.setLayout(new GridLayout(1, 2));
        
        gerberFile.setColumns(20);
        gerberFile.setSize(200, 200);
        
        gerberPanel.add(new JScrollPane(gerberFile), BorderLayout.EAST);
        gerberPanel.add(gerberViewerPanel, BorderLayout.WEST);

        JPanel gCodePanel = new JPanel();
        gCodePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("gCode"));
        gCodePanel.setLayout(new GridLayout(1, 2));

        gCodePanel.add(new JScrollPane(gCodeFile), BorderLayout.EAST);
        gCodePanel.add(gCodeViewerPanel, BorderLayout.WEST);

        content.add(gerberPanel, BorderLayout.EAST);
        content.add(gCodePanel, BorderLayout.WEST);

        //this.setLayout(new GridLayout(2, 1));
        add(content, BorderLayout.CENTER);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        
        
    }

    private void getProperties() {
        String propFileName = "com/agile/resources/string.properties";
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
        try {
            prop.load(inputStream);
            if (inputStream == null) {
                JOptionPane.showMessageDialog(this,
                        "Fichero string.properties no se encontro",
                        "Error",
                        JOptionPane.ERROR_MESSAGE);
            }
        } catch (IOException ex) {
            Logger.getLogger(Frame.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    private void makeMenu() {
        JMenuBar menuBar = new JMenuBar();
        setJMenuBar(menuBar);
        JMenu fileMenu = new JMenu(prop.getProperty("menu_file"));

        menuBar.add(fileMenu); // Add the file menu

        /*JMenuItem elementoAcerca = new JMenuItem(prop.getProperty("open_file"));
         elementoAcerca.setMnemonic('c');
         fileMenu.add(elementoAcerca);
         elementoAcerca.addActionListener(
         new ActionListener() {  // clase interna anónima

         // mostrar cuadro de diálogo de mensaje cuando el usuario seleccione Acerca de...
         public void actionPerformed(ActionEvent evento) {
         /*JOptionPane.showMessageDialog( new JFrame(),
         "Éste es un ejemplo\ndel uso de menús",
         "Acerca de", JOptionPane.PLAIN_MESSAGE );*/
                        //loadFile();
        //}
        //} // fin de la clase interna anónima
        //); // fin de la llamada a addActionListener*//
        // establecer elemento de menú Salir
        JMenuItem elementoSalir = new JMenuItem("Salir");
        elementoSalir.setMnemonic('S');
        fileMenu.add(elementoSalir);
        elementoSalir.addActionListener(
                new ActionListener() {  // clase interna anónima

                    // terminar la aplicación cuando el usuario haga clic en elementoSalir
                    public void actionPerformed(ActionEvent evento) {
                        System.exit(0);
                    }

                } // fin de la clase interna anónima

        ); // fin de la llamada a addActionListener

    }

    private void makeTool() {
        JToolBar toolbar = new JToolBar();
        toolbar.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
        JLabel fileLbl = new JLabel("Fichero Gerber :");

        JTextField fileTxt = new JTextField();
        fileTxt.setColumns(45);
        fileTxt.setMaximumSize(fileTxt.getPreferredSize());

        JButton browserBtn = new JButton("...");
        browserBtn.setMaximumSize(browserBtn.getPreferredSize());

        JButton loadBtn = new JButton("load");
        loadBtn.setMaximumSize(loadBtn.getPreferredSize());

        JButton generategCodeBtn = new JButton("Generar gCode");
        generategCodeBtn.setMaximumSize(generategCodeBtn.getPreferredSize());

        JButton sendLocationsBtn = new JButton("Enviar Coordenadas");
        sendLocationsBtn.setMaximumSize(generategCodeBtn.getPreferredSize());

        toolbar.add(Box.createRigidArea(new Dimension(20, 1)));
        toolbar.add(fileLbl);
        toolbar.add(Box.createRigidArea(new Dimension(10, 1)));
        toolbar.add(fileTxt);
        toolbar.add(Box.createRigidArea(new Dimension(10, 1)));
        toolbar.add(browserBtn);
        toolbar.add(Box.createRigidArea(new Dimension(10, 1)));
        toolbar.add(loadBtn);
        toolbar.add(Box.createRigidArea(new Dimension(10, 1)));
        toolbar.add(generategCodeBtn);
        toolbar.add(Box.createRigidArea(new Dimension(10, 1)));
        toolbar.add(sendLocationsBtn);

        browserBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                //loadFile();
                test_gerber();
            }
        });
        add(toolbar, BorderLayout.PAGE_START);
    }

    private void test_gerber() {
        String path = "E:\\agile-pipei\\RS-274X\\enabtmr.GBL";
        String line;
       
        // create and display dialog box to get file name
        File file = new File(path);

        // Make sure the user did not cancel.
            // Find out which file the user selected.
        String in = "";
        try {
            // Open the file.
            BufferedReader input = new BufferedReader(new FileReader(file));

            // Clear the editing area
            gerberFile.setText("");

                // Fill up the ediitng area with the contents of the file being
            // read.
            line = input.readLine();
            while (line != null) {
                gerberFile.append(line + "\n");
                in += line;
                line = input.readLine();
            }

            // Close the file
            input.close();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(gerberFile, "Can't load file "
                    + e.getMessage());
        }

        Plotter pl = new Plotter();
        pl.setScale(25.0, 25.0);
        pl.setSize(300, 600);
        pl.setGraphics(gerberViewerPanel.getGraphics());

        if (pl.plotInput(in) == false) {
            System.out.println("Error: Plotter unable to plot input.");
        } else {
            System.out.println("Debug: Plotting successful.");
        }

    }

    private void loadFile() {
        String line;
        File file;

        // create and display dialog box to get file name
        JFileChooser dialog = new JFileChooser();

        // Make sure the user did not cancel.
        if (dialog.showOpenDialog(gerberFile) == JFileChooser.APPROVE_OPTION) {
            // Find out which file the user selected.
            file = dialog.getSelectedFile();

            String in = "";
            try {
                // Open the file.
                BufferedReader input = new BufferedReader(new FileReader(file));

                // Clear the editing area
                gerberFile.setText("");

                // Fill up the ediitng area with the contents of the file being
                // read.
                line = input.readLine();
                while (line != null) {
                    gerberFile.append(line + "\n");
                    in += line;
                    line = input.readLine();
                }

                // Close the file
                input.close();
            } catch (IOException e) {
                JOptionPane.showMessageDialog(gerberFile, "Can't load file "
                        + e.getMessage());
            }

            Plotter pl = new Plotter();
            pl.setScale(10.0, 10.0);
            pl.setSize(400, 600);
            pl.setGraphics(gerberViewerPanel.getGraphics());

            if (pl.plotInput(in) == false) {
                System.out.println("Error: Plotter unable to plot input.");
            } else {
                System.out.println("Debug: Plotting successful.");
            }

        }
    }
}
